<template>
  <form action="/">
    <van-search
        v-model="searchContext"
        show-action
        placeholder="请输入搜索关键词"
        @search="onSearch"
        @cancel="onCancel"
    />
  </form>

  <van-divider content-position="left">已选标签</van-divider>
  <div v-if="activeIds.length === 0">请选择标签</div>
  <van-row gutter="10">
    <van-col span="4" v-for="tag in activeIds" :key="tag">
      <van-tag closeable size="small" type="primary" @close="doClose(tag)">
        {{ tag }}
      </van-tag>
    </van-col>
  </van-row>

  <van-divider content-position="left">选择标签</van-divider>

  <van-tree-select
      v-model:active-id="activeIds"
      v-model:main-active-index="activeIndex"
      :items="tagList"
  />


  <van-button type="primary" block @click="doSearch">搜索</van-button>

</template>

<script setup>
import { useRouter, useRoute } from 'vue-router'
import { ref } from "vue";

const router = useRouter()
const route = useRoute()

const searchContext = ref(""); // 搜索文本绑定 v-model

// 关闭标签
const doClose = (tag) => {
  activeIds.value = activeIds.value.filter((item) => item !== tag);
};

// 已选中的标签
const activeIds = ref([]);
const activeIndex = ref(0);

// 原始标签列表
const originTagList = [
  {
    text: "性别",
    children: [
      { text: "男", id: "男" },
      { text: "女", id: "女" },
    ],
  },
  {
    text: "年纪",
    children: [
      { text: "大一", id: "大一" },
      { text: "大二", id: "大二" },
      { text: "大三", id: "大三" },
      { text: "大四", id: "大四" },
      { text: "研一", id: "研一" },
      { text: "研二", id: "研二" },
      { text: "研三", id: "研三" },
    ],
  },
  {
    text: "技能",
    children: [
      { text: "java", id: "java" },
      { text: "python", id: "python" },
      { text: "c++", id: "c++" },
      { text: "golang", id: "golang" },
      { text: "vue", id: "vue" },
      { text: "react", id: "react" },
    ],
  },
];

const tagList = ref(originTagList);

// 搜索功能  难点真难
const onSearch = () => {
  tagList.value = originTagList.map((parentTag) => {
    // 检查是否存在 children 属性
    if (!parentTag.children) return parentTag;

    const tempParentTag = { ...parentTag };
    tempParentTag.children = parentTag.children.filter((item) =>
        item.text.includes(searchContext.value)
    );
    return tempParentTag;
  });

};

// 取消搜索
const onCancel = () => {
  searchContext.value = ""; // 清空搜索内容
  tagList.value = originTagList; // 恢复原始数据
};

const  doSearch =() =>{
  router.push({
    path: '/user/list',
    query  : {tags : activeIds.value}
  })
}



</script>

<style scoped>
</style>
